﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using mars_server.csharp.model;
using mars_server.csharp.dao;
using mars_server.csharp.dao.impl;
using mars_server.csharp.enums;

namespace mars_server.csharp.AO.impl
{
    public class RelationAOImpl : RelationAO
    {

        private RelationAOImpl() { }
        private static readonly RelationAOImpl instance = new RelationAOImpl();
        public static RelationAOImpl Instance
        {
            get
            {
                return instance;
            }
        }

        RelationManager relationManager = RelationManagerImpl.Instance;

        UserManager userManager = UserManagerImpl.Instance;

        /**
         * 通过userId来获取该用户的好友对象
         * */
        public List<UserDO> queryFriendDOsByUserId(long userId)
        {
            List<RelationDO> relationDOs = relationManager.selectRelationDOsByUserId(userId);
            List<long> friendIds = new List<long>();
            foreach(RelationDO relationDO in relationDOs)
            {
                friendIds.Add(relationDO.friendId);
            }

            return userManager.selectUserDOsByUserIds(friendIds);
        }

        public bool addFriend(long userId, long friendId)
        {
            bool flag = true;
            RelationDO relationDO1 = new RelationDO();
            RelationDO relationDO2 = new RelationDO();
            relationDO1.friendId = friendId;
            relationDO1.userId = userId;

            relationDO2.userId = friendId;
            relationDO2.friendId = userId;

            flag = relationManager.InsertRelationDO(relationDO1);
            flag = relationManager.InsertRelationDO(relationDO2);

            return flag;
        }

        public bool isFriendRelation(long userId, long friendId)
        {
            List<RelationDO> relationDOs = relationManager.selectRelationDOsByUserId(userId);
            foreach(RelationDO relationDO in relationDOs)
            {
                if(friendId == relationDO.friendId)
                {
                    return true;
                }
            }
            return false;
        }

        public bool deleteRelationByRelationDO(long userId, long friendId)
        {
            if(!this.isFriendRelation(userId, friendId))
            {
                return false;
            }
            RelationDO relationDO = new RelationDO();
            relationDO.userId= userId;
            relationDO.friendId = friendId;
            relationManager.deleteRelationDO(relationDO);

            RelationDO relationDO2 = new RelationDO();
            relationDO2.userId = friendId;
            relationDO2.friendId = userId;
            relationManager.deleteRelationDO(relationDO2);

            return true;
        }
    }
}
